package com.borrowed.book.user.service.impl;

import com.borrowed.book.coupon.service.SCouponService;
import com.borrowed.book.system.util.BeanUtils;
import com.borrowed.book.user.domain.SUser;
import com.borrowed.book.user.domain.SelectUserDto;
import com.borrowed.book.user.domain.SelectUserInDto;
import com.borrowed.book.user.exception.UserNotExistException;
import com.borrowed.book.user.mapper.SUserMapper;
import com.borrowed.book.user.service.SUserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SUserServiceImpl implements SUserService {
    @Autowired
    private SUserMapper userMapper;

    @Autowired
    private SCouponService couponService;
    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public SUser selectUserByLoginName(String username, String password) {
        SUser user=userMapper.selectUserByLoginName(username);
        if(user==null){
            throw new UserNotExistException("账号或者密码不正确");
        }else{
            if(!password.equals(user.getPassword())){
                throw new UserNotExistException("账号或者密码不正确");
            }
        }
        return user;
    }

    /**
     * 根据openId查询用户信息
     *
     * @param openId
     */
    @Override
    public SUser selectUserByOpenId(String openId) {
       SUser user=userMapper.selectUserByOpenId(openId);
       if(user==null){
           //如果用户为空，则新建用户
           user=new SUser();
           user.setOpenid(openId);
           user.setCreateTime(new Date());
           user.setGold(new BigDecimal(0));
           userMapper.insert(user);
           //新建用户，生成用户优惠券
           couponService.createNewuserCoupon(openId);
       }
        return user;
    }

    /**
     * 用户一览查询
     *
     * @param inDto
     */
    @Override
    public List<SelectUserDto> selectUserList(SelectUserInDto inDto) throws IllegalAccessException {
        Map<String,Object> map= BeanUtils.getObjectToMap(inDto);
        List<SelectUserDto> userList=userMapper.selectUserList(map);
        return userList;
    }

    /**
     * 用户更新
     *
     * @param user
     */
    @Override
    public void updateUser(SUser user) {
        SUser sysUser = (SUser) SecurityUtils.getSubject().getPrincipal();
        user.setOpenid(sysUser.getOpenid());
        userMapper.updateUserInfo(user);
    }
}
